package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportServiceMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverReport(LocalDate begin, LocalDate end) {
        // 返回 dataList日期列表 字符串
        List<LocalDate> dateListDB = new ArrayList<>();
        while(!begin.equals(end.plusDays(1))) {
            dateListDB.add(begin);
            begin = begin.plusDays(1);  // 日期 +1 天
        }
        String dateList = StringUtils.join(dateListDB, ",");// 用 StringUtils 封装。注意一定要是 lang3 包的

        // 返回 turnoverList营业额列表 字符串
        // select * from orders where begin_time > #{begin} and end_time < #{end} and status = #{status}
        // 查询对应日期的营业额
        List<Double> turnoverListDB = new ArrayList<>();
        for (LocalDate date : dateListDB) {
            // 转换每一天的时间为开始时间到结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 封装每一天的查询条件
            Map map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = reportServiceMapper.turnoverStatistics(map);
            // 由于查出来为 0 时，返回的是 null，所以要判断
            turnover = (turnover == null ? 0.0 : turnover);
            turnoverListDB.add(turnover);
        }
        String turnoverList = StringUtils.join(turnoverListDB, ",");
        // 构建返回对象
        TurnoverReportVO build = TurnoverReportVO.builder().dateList(dateList).turnoverList(turnoverList).build();

        return build;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userReport(LocalDate begin, LocalDate end) {
        // 封装日期列表
        List<LocalDate> dateListDB = new ArrayList<>();
        while (!begin.equals(end.plusDays(1))) {
            dateListDB.add(begin);
            begin = begin.plusDays(1);
        }
        String dateList = StringUtils.join(dateListDB, ",");

        // 封装新增用户 和 用户总量
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateListDB) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            // 先封装用户总量的条件然后查询
            map.put("endTime", endTime);
            Integer newUserNum = reportServiceMapper.userStatistics(map);
            newUserList.add(newUserNum);
            // 然后封装新增用户
            map.put("beginTime", beginTime);
            Integer totalUserNum = reportServiceMapper.userStatistics(map);
            totalUserList.add(totalUserNum);
        }
        String newUser = StringUtils.join(newUserList, ",");
        String totalUser = StringUtils.join(totalUserList, ",");

        UserReportVO build = UserReportVO.builder().dateList(dateList).newUserList(newUser).totalUserList(totalUser).build();

        return build;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dateListDB = new ArrayList<>();
        while (!begin.equals(end.plusDays(1))) {
            dateListDB.add(begin);
            begin = begin.plusDays(1);
        }
        String dateList = StringUtils.join(dateListDB, ",");
        // 订单数列表 select count(id) from orders where order_time > begin and order_time < end;
        // 有效订单数列表 select count(id) from orders where order_time > begin and order_time < end and status = 5;
        List<Integer> orderList = new ArrayList<>();
        List<Integer> validOrderList = new ArrayList<>();

        for (LocalDate date : dateListDB) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            Integer orderNum = reportServiceMapper.orderStatistics(map);
            orderNum = (orderNum == null ? 0 : orderNum);
            orderList.add(orderNum);

            map.put("status", Orders.COMPLETED);
            Integer validOrderNum = reportServiceMapper.orderStatistics(map);
            validOrderNum = (validOrderNum == null ? 0 : validOrderNum);
            validOrderList.add(validOrderNum);
        }
        Integer totalOrderCount = orderList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = (totalOrderCount == 0 ? 0 : validOrderCount.doubleValue() / totalOrderCount);

        OrderReportVO build = OrderReportVO.builder().dateList(dateList)
                .orderCountList(StringUtils.join(orderList, ","))
                .orderCompletionRate(orderCompletionRate)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderList, ","))
                .build();

        return build;
    }

    /**
     * 菜品销量排名统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO salesTop10Report(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = reportServiceMapper.getSalesTop10(beginTime, endTime);

        // 用 stream 流获取集合元素
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");

        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出 Excel 报表
     */
    @Override
    public void exportData(HttpServletResponse response) {
        // 1. 查询数据库，获取营业数据
        LocalDate now = LocalDate.now().minusDays(1);
        LocalDate beginTime = LocalDate.now().minusDays(30);
        // 查询数据概览
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginTime, LocalTime.MIN), LocalDateTime.of(now, LocalTime.MAX));
        // 2. 通过 POI 将数据写入 Excel 文件中
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);
            // 填充数据
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            // 填充时间段
            sheet1.getRow(1).getCell(1).setCellValue("时间：" + beginTime + "--" + now);
            // 填充概览数据
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            // 填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate localDate = beginTime.plusDays(i);
                // 查询本日数据
                BusinessDataVO dayBusinessData = workspaceService.getBusinessData(LocalDateTime.of(localDate, LocalTime.MIN), LocalDateTime.of(localDate, LocalTime.MAX));
                row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(localDate.toString());
                row.getCell(2).setCellValue(dayBusinessData.getTurnover());
                row.getCell(3).setCellValue(dayBusinessData.getValidOrderCount());
                row.getCell(4).setCellValue(dayBusinessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(dayBusinessData.getUnitPrice());
                row.getCell(6).setCellValue(dayBusinessData.getNewUsers());
            }

        // 3. 通过输出流将 Excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            outputStream.close();
            resourceAsStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


